from flask import Flask
from app.config import AppConfig
from app.es_client import ESClient
from app.scheduler import start_scheduler
from app.web.views import bp, init_views
from app.alert import check_and_alert
import threading
import time
import secrets;
from werkzeug.middleware.proxy_fix import ProxyFix


if __name__ == '__main__':
    # 1. 加载配置
    config = AppConfig('config.ini')
    es_conf = config.get_es_config()
    # 2. 初始化ES
    es_client = ESClient(
        host=es_conf['host'],
        port=es_conf['port'],
        scheme=es_conf.get('scheme', 'https'),
        username=es_conf.get('es_user'),
        password=es_conf.get('es_password'),
        verify_certs=False
    )
    if not es_client.ping():
        print('无法连接到Elasticsearch，请检查配置。')
        exit(1)
    print('成功连接到Elasticsearch。')
    # 3. 初始化Flask
    app = Flask(__name__)
    app.register_blueprint(bp)
    app.secret_key = secrets.token_hex(32)
    app.config['PREFERRED_URL_SCHEME'] = 'https'
    app.wsgi_app = ProxyFix(app.wsgi_app, x_prefix=1, x_proto=1, x_host=1)
    init_views(es_client.client, config)
    # 4. 启动Web服务（后台线程）
    web_thread = threading.Thread(target=lambda: app.run(host='0.0.0.0', port=5000, debug=False), daemon=True)
    web_thread.start()
    print('Web服务器已启动，访问: http://localhost:5000')
    # 5. 启动调度器
    scheduler = start_scheduler(check_and_alert, 1, config, es_client)
    # 6. 首次启动时立即执行一次
    print('5秒后立即执行一次检查...')
    time.sleep(5)
    check_and_alert(config, es_client)
    # 7. 主线程保持运行
    try:
        while True:
            time.sleep(1)
    except (KeyboardInterrupt, SystemExit):
        print('正在停止监控程序...')
        scheduler.shutdown()
        print('监控程序已停止。') 